package com.system.insurance.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.system.common.result.Result;
import com.system.insurance.entity.AppletUser;
import com.system.insurance.service.AppletUserService;
import com.system.insurance.utils.AuthContextUtil;
import com.system.insurance.utils.SignUtil;
import com.system.insurance.utils.WechatUtil;
import com.system.insurance.utils.WxUtill;
import io.swagger.annotations.Api;
import io.swagger.models.HttpMethod;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin(origins = "*")
@Api(tags = "下载图片")
@Slf4j
@RequestMapping("/insurance/common")
public class ImageController {


    @Autowired
    private AppletUserService appletUserService;

    @Value("${imageUrl}")
    private String basePath;

    @Value("${urlVideo}")
    private String urlVideo;

    @Value("${qrCodeUrl}")
    private String qrCodeUrl;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件格式
        String subFile= originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成随机的文件名字
        String filename = UUID.randomUUID().toString() + subFile;
        File file1 = new File(basePath);
        //判断存放图片的目录是否存在，不存在则进行创建
        if (!file1.exists()) {
            file1.mkdirs();
        }


        try {
            //错误示范
//            file.transferTo(new File(file1 + filename));
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.ok(filename);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");
            int len = 0;
//            byte[] bytes = new byte[1024];
            byte[] bytes = new byte[4096];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            outputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    /**
     * 生成带参小程序二维码
     *
     * @param
     * @param
     */

    @PostMapping("/qrCode")
    public Result qrCode(String appUserId, MultipartFile file) {


//        String s = AuthContextUtil.get();
//        Integer appUserId = Integer.valueOf(s);

        JSONObject token = WxUtill.getAccessToken();


        if (StringUtils.isNotBlank(token.getString("errcode"))) {
            new Exception("获取access_token失败");
        }

//
//        // 使用前端code获取手机号码 参数为json格式
//        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token.getString("access_token");

        Map<String, Object> retMap = null;

        File file1 = new File(qrCodeUrl);
        //判断存放图片的目录是否存在，不存在则进行创建
        if (!file1.exists()) {
            file1.mkdirs();
        }

        //生成随机的文件名字
        String filename = UUID.randomUUID().toString() + ".jpg";

        try {
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token.getString("access_token"));
//            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("POST");// 提交模式
            httpURLConnection.setRequestProperty("Content-Type", "application/x-javascript; charset=UTF-8");
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
//            paramJson.put("scene", appUserId);
            paramJson.put("scene", URLEncoder.encode(appUserId, "utf-8"));
            paramJson.put("page", "pages/index/main");
            paramJson.put("width", 430);
            paramJson.put("auto_color", true);
            // 是否强制验证路径是否存在
            paramJson.put("check_path", false);
// 当前环境：正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。 默认下面这句代码是注释的，发布版本上生产环境时要注释这句代码
            paramJson.put("env_version", "trial");


            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            /*ByteArrayOutputStream os = new ByteArrayOutputStream();*/


            AppletUser byId = appletUserService.getById(appUserId);

            byId.setQrCode(filename);
            byId.setUpdateTime(LocalDateTime.now());
            appletUserService.updateById(byId);


            OutputStream os = new FileOutputStream(new File(qrCodeUrl + filename ));
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
//            // 上传到服务器


//            file.transferTo(new File(qrCodeUrl + filename));

//            String fileName = CurrentTimeMillisId.next() + ".jpg";
//            String urls = createFilePath(fileName, sourceType);
//            InputStream is = new ByteArrayInputStream(os.toByteArray());
//            String miniCodeUrl = ossFileService.uploadFile(is, urls);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok(filename);
    }



    @PostMapping("/qrCode111")
    @ResponseBody
    public Result cenerateTheQrCode(HttpServletRequest request,String appUserId){
        //调用上面方法，获取accessToken，建议对accessToken进行缓存，
        //appid：小程序appid，appsecret：小程序密钥
        JSONObject token = WxUtill.getAccessToken();
        Map<String, Object> params = new HashMap<>();
        //参数,一个可以直接放入参数例如:1 多个例如：id=1&name=2&...
        params.put("scene", appUserId);
        params.put("path", "pages/index/index"); //扫码后进入小程序的页面位置
        params.put("width", 430);//不是必须，需要的宽度，默认430x430，最小280最大1280
        params.put("auto_color", true);
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 接口
        HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+ token.getString("access_token"));
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        String body = JSON.toJSONString(params);//必须是json模式的 post
        StringEntity entity = null;


        //生成随机的文件名字
        String filename = UUID.randomUUID().toString() + ".jpg";
        try {
            entity = new StringEntity(body);
            entity.setContentType("image/png");//也可以是image/jpg
            httpPost.setEntity(entity);
            HttpResponse response;
            response = httpClient.execute(httpPost);
            InputStream inputStream = response.getEntity().getContent();
            String name = filename+".png";//文件名加后缀，跟上面对应
            String path = qrCodeUrl;//图片保存路径
            SignUtil.saveToImgByInputStream(inputStream,path,name);  //保存图片

            AppletUser byId = appletUserService.getById(appUserId);

            byId.setQrCode(filename);
            byId.setUpdateTime(LocalDateTime.now());
            appletUserService.updateById(byId);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok(filename);
    }

}
